#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

// 函数声明
int calculate_fx(int x);
int calculate_fy(int y);
int calculate_fxy(int x, int y);

int main() {
    int x, y;
    printf("请输入x和y的值(用空格分隔): ");
    scanf("%d %d", &x, &y);

    pid_t pid_fx, pid_fy, pid_fxy;
    int status;
    int pipe_fx[2], pipe_fy[2];

    // 创建管道
    if (pipe(pipe_fx) == -1 || pipe(pipe_fy) == -1) {
        perror("管道创建失败");
        exit(EXIT_FAILURE);
    }

    // 创建计算f(x)的进程
    pid_fx = fork();
    if (pid_fx == 0) {
        close(pipe_fx[0]); // 关闭读端
        int result = calculate_fx(x);
        write(pipe_fx[1], &result, sizeof(result));
        close(pipe_fx[1]);
        exit(0);
    } else if (pid_fx < 0) {
        perror("创建f(x)进程失败");
        exit(EXIT_FAILURE);
    }

    // 创建计算f(y)的进程
    pid_fy = fork();
    if (pid_fy == 0) {
        close(pipe_fy[0]); // 关闭读端
        int result = calculate_fy(y);
        write(pipe_fy[1], &result, sizeof(result));
        close(pipe_fy[1]);
        exit(0);
    } else if (pid_fy < 0) {
        perror("创建f(y)进程失败");
        exit(EXIT_FAILURE);
    }

    // 创建计算f(x,y)的进程
    pid_fxy = fork();
    if (pid_fxy == 0) {
        close(pipe_fx[1]); // 关闭写端
        close(pipe_fy[1]); // 关闭写端

        int fx, fy;
        read(pipe_fx[0], &fx, sizeof(fx));
        read(pipe_fy[0], &fy, sizeof(fy));

        close(pipe_fx[0]);
        close(pipe_fy[0]);

        int result = calculate_fxy(fx, fy);
        printf("f(%d,%d) = %d\n", x, y, result);
        exit(0);
    } else if (pid_fxy < 0) {
        perror("创建f(x,y)进程失败");
        exit(EXIT_FAILURE);
    }

    // 父进程等待所有子进程结束
    close(pipe_fx[0]);
    close(pipe_fx[1]);
    close(pipe_fy[0]);
    close(pipe_fy[1]);

    waitpid(pid_fx, &status, 0);
    waitpid(pid_fy, &status, 0);
    waitpid(pid_fxy, &status, 0);

    return 0;
}

// 计算f(x)的函数
int calculate_fx(int x) {
    if (x == 1) {
        return 1;
    } else if (x > 1) {
        return calculate_fx(x - 1) * x;
    }
    return 0;
}

// 计算f(y)的函数
int calculate_fy(int y) {
    if (y == 1 || y == 2) {
        return 1;
    } else if (y > 2) {
        return calculate_fy(y - 1) + calculate_fy(y - 2);
    }
    return 0;
}

// 计算f(x,y)的函数
int calculate_fxy(int fx, int fy) {
    return fx + fy;
}
